package trie

import (
	"errors"
	"strings"
)

type Router struct {
	root map[string]*node
}

func (r *Router) AddRouter(pattern string, data string) {
	if r.root == nil {
		r.root = make(map[string]*node)
	}
	root, ok := r.root["/"]
	if !ok {
		//创建跟路由
		root = &node{part: "/"}
		r.root["/"] = root
	}

	parts := strings.Split(strings.Trim(pattern, "/"), "/")
	for _, part := range parts {
		if part == "" {
			panic("不符合格式")
		}
		root = root.addNode(part)
	}
	//循环结束后 该root是叶子节点，需要保存data值
	root.data = data
}
func (r *Router) GetRouter(pattern string) (*node, error) {
	root, ok := r.root["/"]
	if !ok {
		//创建跟路由
		root = &node{part: "/"}
		r.root["/"] = root
	}
	parts := strings.Split(strings.Trim(pattern, "/"), "/")
	for _, part := range parts {
		if part == "" {
			return nil, errors.New("pattern格式不对")
		}
		root = root.getNode(part)
		if root == nil {
			return nil, errors.New("pattern不存在")
		}
	}
	return root, nil
}

type node struct {
	//当前节点的唯一标识
	part string
	//子节点数
	children map[string]*node
	//当前节点需要保存的数据
	data string
}

// 添加节点
func (n *node) addNode(part string) *node {
	if n.children == nil {
		n.children = make(map[string]*node)
	}
	child, ok := n.children[part]
	if !ok {
		child = &node{part: part}
		n.children[part] = child
	}
	return child
}

func (n *node) getNode(part string) *node {
	if n.children == nil {
		return nil
	}
	child, ok := n.children[part]
	if !ok {
		return nil
	}
	return child
}
